#!/usr/bin/env python
# -*- coding: latin-1 -*-

import gtk
import os, sys
import string
from random import randrange
from xml.dom import minidom

sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),".."))
import Process

fileXML = ""

colorBg = "#FFFFFF"
colorBg1 = "#562525"
colorBg2 = "#784949"

def ClickAccept(widget):

	global fileXML
	global colorBg
	global colorBg1
	global colorBg2

	# recorremos todos los directorios
	files = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].split("\n")

	pathDirectories = Process.getCurrentDirectory()

	fileXML = pathDirectories+"/"+".comments_nautilus.xml"

	widthImg = int(spinWidth.get_value())

	filesArray = []

	for f in files:
		if f != "":
			if not os.path.isdir(f):
				if Process.getExtension(f)=="JPG" or Process.getExtension(f)=="PNG":
					path = Process.getPath(f)
					fileName = Process.getFile(f)
					fileNameCopy = Process.getName(fileName) + "_polaroid.png"
					fileCopy = path + "/" + fileNameCopy

					fileNameShadow = Process.getName(fileName) + "_shadow.png"
					fileShadow = path + "/" + fileNameShadow

					#filesArray.append(fileCopy)
					filesArray.append(fileShadow)

					pb = gtk.gdk.pixbuf_new_from_file( f )

					if pb.get_height()<pb.get_width():
						Process.ProcessFileByArgument(
							"convert -resize " + str(widthImg) + "x \"" + f + "\" \"" + fileCopy + "\"")
					else:
						Process.ProcessFileByArgument(
							"convert -resize x" + str(widthImg) + " \"" + f + "\" \"" + fileCopy + "\"")

					pb = gtk.gdk.pixbuf_new_from_file( fileCopy )

					# polaroid

					borderPolaroid = widthImg/30

					Process.ProcessFileByArgument(
						"convert -size " + str(pb.get_width()+(borderPolaroid*2)) + "x" + str(pb.get_height()+(borderPolaroid*6)) + " gradient:#f0f0ff-#f0f0ff -draw \"image Over " + str(borderPolaroid) + "," + str(borderPolaroid) + " "+str(pb.get_width())+","+str(pb.get_height())+" '" + fileCopy + "'\" \"" + fileCopy + "\"")

					# poner comentario
					if cbComment.get_active() == True:
						pb = gtk.gdk.pixbuf_new_from_file( fileCopy )
						data = readPhotoXML(fileName)
						if data[0]!="":
							Process.ProcessFileByArgument(
								"convert -background none -fill transparent -font helvetica -fill black -pointsize " + str(int(pb.get_height()/14)) + " -draw \"text " + str(borderPolaroid) + "," + str(pb.get_height()-(borderPolaroid*2)) +" '" + data[0] + "'\" \"" + fileCopy + "\" \"" + fileCopy + "\"")


					pb = gtk.gdk.pixbuf_new_from_file( fileCopy )

					#Process.ProcessFileByArgument(
					#	"convert -fill transparent -stroke #000000 -strokewidth 1 -draw \"rectangle 0,0 "+str(pb.get_width())+","+str(pb.get_height())+"\" -draw \"rectangle " + str(borderPolaroid) + "," + str(borderPolaroid) + " "+str(widthPhoto)+","+str(heightPhoto)+"\" \"" + fileCopy + "\" \"" + fileCopy + "\"")

					Process.ProcessFileByArgument(
						"convert -background none -fill transparent -wave " + str(pb.get_width()*0.01) + "x" + str(pb.get_height()*2) + " \"" + fileCopy + "\" \"" + fileCopy + "\"")

					Process.ProcessFileByArgument(
						"convert -background none -fill transparent -bordercolor transparent -border 10 -background none -rotate " + str(randrange(-10,10)) + " \"" + fileCopy + "\" \"" + fileCopy + "\"")

					# redimensionamos de nuevo con el filo polaroid
					if pb.get_height()<pb.get_width():
						Process.ProcessFileByArgument(
							"convert -resize " + str(widthImg) + "x \"" + fileCopy + "\" \"" + fileCopy + "\"")
					else:
						Process.ProcessFileByArgument(
							"convert -resize x" + str(widthImg) + " \"" + fileCopy + "\" \"" + fileCopy + "\"")

					# ponemos sombra
					Process.ProcessFileByArgument(
						"convert \"" + fileCopy + "\"  -channel A  -blur 0x6  -channel RG -fx 0  -channel B -fx .25 \"" + fileShadow + "\"")

					Process.ProcessFileByArgument(
						"convert \"" + fileCopy + "\" -background none -gravity SouthEast -splice 6x6+0+0 \"" + fileShadow + "\" -compose Dst_Over -composite \"" + fileCopy + "\" ")

					pb = gtk.gdk.pixbuf_new_from_file( fileCopy )

					if radBgSolid.get_active() == True:
						Process.ProcessFileByArgument(
							"convert -size " + str(pb.get_width()) + "x" + str(pb.get_height()) + " gradient:" + colorBg + "-" + colorBg + " -draw \"image Over 0,0 "+str(pb.get_width())+","+str(pb.get_height())+" '" + fileCopy + "'\"" + " \"" + fileCopy + "\"")

					if radBgGradient.get_active() == True:
						Process.ProcessFileByArgument(
							"convert -size " + str(pb.get_width()) + "x" + str(pb.get_height()) + " gradient:" + colorBg1 + "-" + colorBg2 + " -draw \"image Over 0,0 "+str(pb.get_width())+","+str(pb.get_height())+" '" + fileCopy + "'\"" + " \"" + fileCopy + "\"")

	for f in filesArray:
		Process.ProcessFileByArgument(
			"rm \""+f+"\"")

	gtk.main_quit()

def ClickCancel(widget):
	gtk.main_quit()


def readPhotoXML(f):
	global fileXML
	if os.path.isfile(fileXML):
		dom = minidom.parse(fileXML)
		for node in dom.getElementsByTagName('photo'):
			if node.attributes["file"].value == f:
				return [node.attributes["title"].value, node.attributes["comment"].value]

	return ["",""]

def ClickColor(widget, data):
	global colorBg
	global colorBg1
	global colorBg2

	colorseldlg = gtk.ColorSelectionDialog("Seleccionar color")

	if data == "__bg__":
		colorseldlg.colorsel.set_current_color(gtk.gdk.color_parse(colorBg))
	
	if data == "__bg1__":
		colorseldlg.colorsel.set_current_color(gtk.gdk.color_parse(colorBg1))

	if data == "__bg2__":
		colorseldlg.colorsel.set_current_color(gtk.gdk.color_parse(colorBg2))

	response = colorseldlg.run()

	if response == gtk.RESPONSE_OK:
		if data == "__bg__":
			colorBg = gtk.color_selection_palette_to_string([colorseldlg.colorsel.get_current_color()]) 
			btnColor.modify_bg(gtk.STATE_NORMAL, colorseldlg.colorsel.get_current_color())
		if data == "__bg1__":
			colorBg1 = gtk.color_selection_palette_to_string([colorseldlg.colorsel.get_current_color()]) 
			btnColorBg1.modify_bg(gtk.STATE_NORMAL, colorseldlg.colorsel.get_current_color())
		if data == "__bg2__":
			colorBg2 = gtk.color_selection_palette_to_string([colorseldlg.colorsel.get_current_color()]) 
			btnColorBg2.modify_bg(gtk.STATE_NORMAL, colorseldlg.colorsel.get_current_color())

	colorseldlg.destroy()

def ToggledBg(widget, data):
	btnColor.set_sensitive(radBgSolid.get_active())
	btnColorBg1.set_sensitive(radBgGradient.get_active())
	btnColorBg2.set_sensitive(radBgGradient.get_active())

# PROGRAMA

if Process.verifyCommands("convert%ImageMagick")==False:
	sys.exit()

w = gtk.Window(gtk.WINDOW_TOPLEVEL)
w.set_title("Covertir a polaroid")
w.set_border_width(20)

w.connect("destroy", gtk.main_quit) 

# tabla de la miniatura

tableMin = gtk.Table(2, 1, False)
tableMin.set_border_width(10)

tableMin.set_row_spacings(8)
tableMin.set_col_spacings(8)

aligImg = gtk.Alignment(0.0, 0.0)
lImg = gtk.Label()
lImg.set_markup("<b>Imagen</b>")
aligImg.add(lImg)

tableMin.attach(aligImg, 0, 2, 0, 1)

lWidth = gtk.Label("Ancho:")

tableMin.attach(lWidth, 0, 1, 1, 2)

adjWidth= gtk.Adjustment(1.0, 1.0, 1024.0, 1.0, 5.0, 0.0)
spinWidth = gtk.SpinButton(adjWidth, 0, 0)
spinWidth.set_value(800)

tableMin.attach(spinWidth, 1, 2, 1, 2)

cbComment = gtk.CheckButton("Poner títulos de los comentarios a las fotos")

cbComment.set_active(True);

tableMin.attach(cbComment, 1, 2, 2, 3)

aligBg = gtk.Alignment(0.0, 0.0)
lBg = gtk.Label()
lBg.set_markup("<b>Fondo</b>")
aligBg.add(lBg)

tableMin.attach(aligBg, 0, 2, 3, 4)

# color fondo

radBgTransparent = gtk.RadioButton(None, "Fondo transparente")
radBgTransparent.set_active(True)
radBgTransparent.connect("toggled", ToggledBg, "rad1")
tableMin.attach(radBgTransparent, 1, 2, 4, 5)

radBgSolid = gtk.RadioButton(radBgTransparent, "Fondo con color sólido")
radBgSolid.connect("toggled", ToggledBg, "rad2")
tableMin.attach(radBgSolid, 1, 2, 5, 6)

aligButtonColor = gtk.Alignment(1.0, 0.0)

btnColor = gtk.Button()

btnColor.set_size_request(25,25)

btnColor.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(colorBg))

btnColor.set_sensitive(False)

btnColor.connect("clicked", ClickColor, "__bg__")

aligButtonColor.add(btnColor)

tableMin.attach(aligButtonColor, 0, 1, 5, 6)

radBgGradient = gtk.RadioButton(radBgTransparent, "Fondo con color gradiente")
radBgGradient.connect("toggled", ToggledBg, "rad3")
tableMin.attach(radBgGradient, 1, 2, 6, 7)


boxButtonsColorBg = gtk.HBox(True, 4)

aligButtonColorBg = gtk.Alignment(1.0, 0.0)

btnColorBg1 = gtk.Button()

btnColorBg1.set_size_request(25,25)

btnColorBg1.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(colorBg1))

btnColorBg1.set_sensitive(False)

btnColorBg1.connect("clicked", ClickColor, "__bg1__")

boxButtonsColorBg.pack_start(btnColorBg1, False, False, 0)

btnColorBg2 = gtk.Button()

btnColorBg2.set_size_request(25,25)

btnColorBg2.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(colorBg2))

btnColorBg2.set_sensitive(False)

btnColorBg2.connect("clicked", ClickColor, "__bg2__")

boxButtonsColorBg.pack_start(btnColorBg2, False, False, 0)

aligButtonColorBg.add(boxButtonsColorBg)

tableMin.attach(aligButtonColorBg, 0, 1, 6, 7)


# botones

aligButtons = gtk.Alignment(1.0, 0.0)
boxButtons = gtk.HBox(True, 4)

bCancel = gtk.Button("Cancelar", gtk.STOCK_CANCEL)

bCancel.connect("clicked", ClickCancel)

boxButtons.pack_start(bCancel, False, False, 0)

bAccept = gtk.Button("Aceptar", gtk.STOCK_OK)

bAccept.connect("clicked", ClickAccept)

boxButtons.pack_start(bAccept, False, False, 0)

aligButtons.add(boxButtons)
tableMin.attach(aligButtons, 1, 2, 7, 8)

w.add(tableMin)
w.show_all()
gtk.main()
